{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "12058891",
   "metadata": {},
   "source": [
    "\n",
    "# 采用变分算法重构半导体双量子点单-三重态量子门\n",
    "\n",
    "## 单量子比特情况\n",
    "\n",
    "## 采用脉冲强度不变，持续时间变的方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "d6d54622",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.504964715598844\n",
      "0.9126772157609289\n",
      "0.9893397160188581\n",
      "0.998743377627901\n",
      "0.9998522498645346\n",
      "\n",
      "fid: 0.999994275711438\n",
      "\n",
      "params: [2.19896871 0.08977132 1.10727439 0.63598394 0.6257678  0.58398319\n",
      " 0.93714334 0.97712595]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(0*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(0*s_z+s_x)\n",
    "\n",
    "\n",
    "def _matrix_1(coeff):\n",
    "    return expm(-1j*(1*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_1(coeff):\n",
    "    return -1j*_matrix_1(coeff)@(1*s_z+s_x)\n",
    "\n",
    "\n",
    "def _matrix_2(coeff):\n",
    "    return expm(-1j*(2*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_2(coeff):\n",
    "    return -1j*_matrix_2(coeff)@(2*s_z+s_x)\n",
    "\n",
    "def _matrix_3(coeff):\n",
    "    return expm(-1j*(3*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_3(coeff):\n",
    "    return -1j*_matrix_3(coeff)@(3*s_z+s_x)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "gate_1 = gene_univ_parameterized_gate('gete_1', _matrix_1, _diff_matrix_1)\n",
    "gate_2 = gene_univ_parameterized_gate('gete_2', _matrix_2, _diff_matrix_2)\n",
    "gate_3 = gene_univ_parameterized_gate('gete_3', _matrix_3, _diff_matrix_3)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_1('01').on(0)\n",
    "circ += gate_2('02').on(0)\n",
    "circ += gate_3('03').on(0)\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_1('11').on(0)\n",
    "circ += gate_2('12').on(0)\n",
    "circ += gate_3('13').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "lr = 0.1 \n",
    "params = 3 * np.random.rand(8)\n",
    "\n",
    "for i in range(100):\n",
    "    f, g = grad_ops(params, np.array([[1.],[0.]]), np.array([[0.],[1.]]))\n",
    "    f, g = grad_ops(params, np.array([[0.],[1.]]), np.array([[1.],[0.]]))\n",
    "    params = abs(params + lr * np.squeeze(g).real)\n",
    "    if i % 20 == 0:\n",
    "        print(f[0,0].real)\n",
    "        \n",
    "[theta00, theta01, theta02, theta03, theta10, theta11, theta12, theta13] = params\n",
    "pr = {'00':theta00, '01':theta01, '02':theta02, '03':theta03, '10':theta10, '11':theta11, '12':theta12, '13':theta13}\n",
    "state = circ.get_qs(pr=pr)\n",
    "fid = np.abs(np.vdot(state, [0,1]))\n",
    "\n",
    "print('\\nfid:',fid)\n",
    "print('\\nparams:',params)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5cf7200",
   "metadata": {},
   "source": [
    "只采用 0 和 1 两个分立动作，实现任意单量子比特幺正算符。对多个算符进行验证训练。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "dedea826",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "进度: 100/100  acc: 1.0000000000000004\n",
      "平均保真度为： 0.9980107389783618\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "import sys\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(0*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(0*s_z+s_x)\n",
    "\n",
    "\n",
    "def _matrix_1(coeff):\n",
    "    return expm(-1j*(1*s_z+s_x)*coeff)\n",
    "\n",
    "def _diff_matrix_1(coeff):\n",
    "    return -1j*_matrix_1(coeff)@(1*s_z+s_x)\n",
    "\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "gate_1 = gene_univ_parameterized_gate('gete_1', _matrix_1, _diff_matrix_1)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_1('01').on(0)\n",
    "circ += gate_0('10').on(0)\n",
    "circ += gate_1('11').on(0)\n",
    "circ += gate_0('20').on(0)\n",
    "circ += gate_1('21').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "lr = 0.05\n",
    "acc_list = []\n",
    "for i in range(len(u_mats)):\n",
    "    params = 2*np.pi* np.random.rand(len(circ.params_name))\n",
    "    for j in range(len(train_x)):\n",
    "        f, g = grad_ops(params, train_x[j], train_y[i,j])\n",
    "        params = abs(params + lr * np.squeeze(g).real)\n",
    "        \n",
    "    final_state = []\n",
    "    for j in range(len(eval_x)):\n",
    "        sim.reset()\n",
    "        sim.set_qs(eval_x[j])\n",
    "        sim.apply_circuit(circ, params)\n",
    "        final_state.append(sim.get_qs())\n",
    "        \n",
    "        \n",
    "    acc = np.real(np.mean([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    acc_list.append(acc)\n",
    "    print(\"\\r\", end=\"\")\n",
    "    print(f\"进度: {i+1}/{len(u_mats)} \",  'acc:', acc, end=\"\")\n",
    "    \n",
    "print('\\n平均保真度为：', np.mean(acc_list))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cbacd44d",
   "metadata": {},
   "source": [
    "## 采用变强度，不变持续时间的脉冲，实现任意单量子比特门。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "id": "245995b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "进度: 1/32  mean_infid: 0.3120028681405761 max_infid 0.43493070693417857\n",
      "进度: 2/32  mean_infid: 0.33700488537752704 max_infid 0.5845074295204774"
     ]
    },
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_16360\\1470401476.py\u001b[0m in \u001b[0;36m<module>\u001b[1;34m\u001b[0m\n\u001b[0;32m     68\u001b[0m     \u001b[0mparams\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpi\u001b[0m\u001b[1;33m*\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrandom\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mrand\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcirc\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mparams_name\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     69\u001b[0m     \u001b[1;32mfor\u001b[0m \u001b[0mj\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtrain_x\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 70\u001b[1;33m         \u001b[0mf\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mg\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mgrad_ops\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mparams\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mtrain_x\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mj\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mtrain_y\u001b[0m\u001b[1;33m[\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mj\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     71\u001b[0m         \u001b[0mparams\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mabs\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mparams\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0mlr\u001b[0m \u001b[1;33m*\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msqueeze\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mg\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mreal\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     72\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\mindquantum\\simulator\\simulator.py\u001b[0m in \u001b[0;36m__call__\u001b[1;34m(self, *args)\u001b[0m\n\u001b[0;32m    401\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    402\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0m__call__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 403\u001b[1;33m         \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mgrad_ops\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0margs\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    404\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    405\u001b[0m     \u001b[1;32mdef\u001b[0m \u001b[0mset_str\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0ms\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\mindquantum\\simulator\\simulator.py\u001b[0m in \u001b[0;36mgrad_ops\u001b[1;34m(*inputs)\u001b[0m\n\u001b[0;32m    299\u001b[0m                                                                    \u001b[0mcirc_right\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mget_cpp_obj\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mhermitian\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;32mTrue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0minputs0\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    300\u001b[0m                                                                    \u001b[0minputs1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mencoder_params_name\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mansatz_params_name\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 301\u001b[1;33m                                                                    batch_threads, mea_threads, simulator_left.sim)\n\u001b[0m\u001b[0;32m    302\u001b[0m             \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    303\u001b[0m                 f_g1_g2 = self.sim.hermitian_measure_with_grad([i.get_cpp_obj()\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\mindquantum\\core\\gates\\basicgate.py\u001b[0m in \u001b[0;36m_diff_matrix\u001b[1;34m(self, theta)\u001b[0m\n\u001b[0;32m    294\u001b[0m             \u001b[1;32mif\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdaggered\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    295\u001b[0m                 \u001b[1;32mreturn\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mconj\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmatrix_generator\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtheta\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mT\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 296\u001b[1;33m             \u001b[1;32mreturn\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdiff_matrix_generator\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mtheta\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    297\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    298\u001b[0m         \u001b[1;32mdef\u001b[0m \u001b[0mhermitian\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_16360\\1470401476.py\u001b[0m in \u001b[0;36m_diff_matrix_0\u001b[1;34m(coeff)\u001b[0m\n\u001b[0;32m     28\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     29\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m_diff_matrix_0\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoeff\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 30\u001b[1;33m     \u001b[1;32mreturn\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m1j\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0m_matrix_0\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoeff\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m@\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms_z\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mdt\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     31\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     32\u001b[0m \u001b[0mgate_0\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mgene_univ_parameterized_gate\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'gete_0'\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0m_matrix_0\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0m_diff_matrix_0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_16360\\1470401476.py\u001b[0m in \u001b[0;36m_matrix_0\u001b[1;34m(coeff)\u001b[0m\n\u001b[0;32m     25\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     26\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m_matrix_0\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoeff\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 27\u001b[1;33m     \u001b[1;32mreturn\u001b[0m \u001b[0mexpm\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m-\u001b[0m\u001b[1;36m1j\u001b[0m\u001b[1;33m*\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoeff\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0ms_z\u001b[0m\u001b[1;33m+\u001b[0m\u001b[0ms_x\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mdt\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m     28\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m     29\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m_diff_matrix_0\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mcoeff\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\scipy\\linalg\\matfuncs.py\u001b[0m in \u001b[0;36mexpm\u001b[1;34m(A)\u001b[0m\n\u001b[0;32m    253\u001b[0m     \u001b[1;31m# Input checking and conversion is provided by sparse.linalg.expm().\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    254\u001b[0m     \u001b[1;32mimport\u001b[0m \u001b[0mscipy\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msparse\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlinalg\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 255\u001b[1;33m     \u001b[1;32mreturn\u001b[0m \u001b[0mscipy\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0msparse\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlinalg\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mexpm\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mA\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    256\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    257\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\scipy\\sparse\\linalg\\matfuncs.py\u001b[0m in \u001b[0;36mexpm\u001b[1;34m(A)\u001b[0m\n\u001b[0;32m    589\u001b[0m             [  0.        ,   0.        ,  20.08553692]])\n\u001b[0;32m    590\u001b[0m     \"\"\"\n\u001b[1;32m--> 591\u001b[1;33m     \u001b[1;32mreturn\u001b[0m \u001b[0m_expm\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mA\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0muse_exact_onenorm\u001b[0m\u001b[1;33m=\u001b[0m\u001b[1;34m'auto'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    592\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    593\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\scipy\\sparse\\linalg\\matfuncs.py\u001b[0m in \u001b[0;36m_expm\u001b[1;34m(A, use_exact_onenorm)\u001b[0m\n\u001b[0;32m    669\u001b[0m     \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    670\u001b[0m         \u001b[0ms\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mmax\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mceil\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mlog2\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0meta_5\u001b[0m \u001b[1;33m/\u001b[0m \u001b[0mtheta_13\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 671\u001b[1;33m     \u001b[0ms\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0ms\u001b[0m \u001b[1;33m+\u001b[0m \u001b[0m_ell\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m**\u001b[0m\u001b[1;33m-\u001b[0m\u001b[0ms\u001b[0m \u001b[1;33m*\u001b[0m \u001b[0mh\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mA\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m13\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    672\u001b[0m     \u001b[0mU\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mV\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mh\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mpade13_scaled\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ms\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    673\u001b[0m     \u001b[0mX\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_solve_P_Q\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mU\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mV\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mstructure\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mstructure\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\scipy\\sparse\\linalg\\matfuncs.py\u001b[0m in \u001b[0;36m_ell\u001b[1;34m(A, m)\u001b[0m\n\u001b[0;32m    848\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    849\u001b[0m     \u001b[1;31m# Compute the one-norm of matrix power p of abs(A).\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 850\u001b[1;33m     \u001b[0mA_abs_onenorm\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0m_onenorm_matrix_power_nnm\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mabs\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mA\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m*\u001b[0m\u001b[0mm\u001b[0m \u001b[1;33m+\u001b[0m \u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    851\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    852\u001b[0m     \u001b[1;31m# Treat zero norm as a special case.\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;32mD:\\Anaconda\\envs\\Mind_Quantum\\lib\\site-packages\\scipy\\sparse\\linalg\\matfuncs.py\u001b[0m in \u001b[0;36m_onenorm_matrix_power_nnm\u001b[1;34m(A, p)\u001b[0m\n\u001b[0;32m    108\u001b[0m     \u001b[0mM\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mA\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mT\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    109\u001b[0m     \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mp\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m--> 110\u001b[1;33m         \u001b[0mv\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mM\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mdot\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mv\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m    111\u001b[0m     \u001b[1;32mreturn\u001b[0m \u001b[0mnp\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmax\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mv\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m    112\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "\n",
    "mean_infid_list = []\n",
    "max_infid_list = []\n",
    "\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    params = 2*np.pi* np.random.rand(len(circ.params_name))\n",
    "    for j in range(len(train_x)):\n",
    "        f, g = grad_ops(params, train_x[j], train_y[i,j])\n",
    "        params = abs(params + lr * np.squeeze(g).real)\n",
    "        \n",
    "    final_state = []\n",
    "    for j in range(len(eval_x)):\n",
    "        sim.reset()\n",
    "        sim.set_qs(eval_x[j])\n",
    "        sim.apply_circuit(circ, params)\n",
    "        final_state.append(sim.get_qs())\n",
    "        \n",
    "    mean_infid = 1-np.real(np.mean([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    max_infid = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    mean_infid_list.append(mean_infid)\n",
    "    max_infid_list.append(max_infid)\n",
    "#     print(\"\\r\", end=\"\")\n",
    "    print(f\"\\n进度: {i+1}/{len(u_mats)} \",  'mean_infid:', mean_infid, 'max_infid', max_infid, end=\"\")\n",
    "    \n",
    "print('\\nmean_infid：', np.mean(mean_infid_list))\n",
    "print('\\nmax_infid：', np.mean(max_infid_list))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ba85bf73",
   "metadata": {},
   "source": [
    "# 用 abs 的自定义 MQLayer, 初始化方式为全 1 初始化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "12e11ce8",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "进度: 1/32  infid: 1.8107737531636303e-13 error: 3.2218672174622043e-13 iter_num: 500\n",
      "\n",
      "进度: 2/32  infid: 1.638911228951656e-12 error: 2.155164935402354e-12 iter_num: 1000\n",
      "\n",
      "进度: 3/32  infid: 6.056693477862751e-07 error: 8.097765978876126e-07 iter_num: 1000\n",
      "\n",
      "进度: 4/32  infid: 2.1347088050571728e-06 error: 3.922348002727283e-06 iter_num: 1000\n",
      "\n",
      "进度: 5/32  infid: 9.747758156208874e-14 error: 1.3100631690576847e-13 iter_num: 500\n",
      "\n",
      "进度: 6/32  infid: 3.0732875283545624e-06 error: 5.7128267495487606e-06 iter_num: 1500\n",
      "\n",
      "进度: 7/32  infid: 5.942056846564014e-10 error: 7.782662292399323e-10 iter_num: 3000\n",
      "\n",
      "进度: 8/32  infid: 2.05613304160579e-13 error: 3.4372504842394846e-13 iter_num: 500\n",
      "\n",
      "进度: 9/32  infid: 1.525790693790441e-08 error: 2.224116224525119e-08 iter_num: 500\n",
      "\n",
      "进度: 10/32  infid: 1.4189760477734126e-12 error: 1.9033663534173684e-12 iter_num: 1000\n",
      "\n",
      "进度: 11/32  infid: 2.0250467969162855e-13 error: 2.8477220581635265e-13 iter_num: 3500\n",
      "\n",
      "进度: 12/32  infid: 2.505910823291657e-08 error: 3.80648668141248e-08 iter_num: 1000\n",
      "\n",
      "进度: 13/32  infid: 1.6986412276764895e-13 error: 2.297051437949449e-13 iter_num: 500\n",
      "\n",
      "进度: 14/32  infid: 1.6753265441593612e-13 error: 2.311484337269576e-13 iter_num: 1000\n",
      "\n",
      "进度: 15/32  infid: 1.5052958879380185e-11 error: 2.121403053223503e-11 iter_num: 1500\n",
      "\n",
      "进度: 16/32  infid: 8.19366796633858e-12 error: 1.1645906461410505e-11 iter_num: 1000\n",
      "\n",
      "进度: 17/32  infid: 1.2323475573339238e-13 error: 1.766364832178624e-13 iter_num: 500\n",
      "\n",
      "进度: 18/32  infid: 2.786428195955537e-07 error: 4.1575219345002523e-07 iter_num: 1000\n",
      "\n",
      "进度: 19/32  infid: 3.3349264805249135e-06 error: 4.669627582054581e-06 iter_num: 1000\n",
      "\n",
      "进度: 20/32  infid: 3.269758197532724e-08 error: 6.487781767372525e-08 iter_num: 1000\n",
      "\n",
      "进度: 21/32  infid: 3.774820678259516e-09 error: 5.339466979670249e-09 iter_num: 500\n",
      "\n",
      "进度: 22/32  infid: 3.9190872769268026e-14 error: 6.716849298982197e-14 iter_num: 1000\n",
      "\n",
      "进度: 23/32  infid: 1.83774966133754e-07 error: 2.5529041891569904e-07 iter_num: 500\n",
      "\n",
      "进度: 24/32  infid: 1.520662510801074e-06 error: 2.0835750229597494e-06 iter_num: 1000\n",
      "\n",
      "进度: 25/32  infid: 3.531772652110021e-10 error: 5.186583384997334e-10 iter_num: 1500\n",
      "\n",
      "进度: 26/32  infid: 1.5576429035490946e-13 error: 2.0827783941967937e-13 iter_num: 2000\n",
      "\n",
      "进度: 27/32  infid: 1.5156236327085182e-06 error: 2.1022876081078223e-06 iter_num: 500\n",
      "\n",
      "进度: 28/32  infid: 1.162403506782539e-13 error: 1.8174350913113813e-13 iter_num: 2000\n",
      "\n",
      "进度: 29/32  infid: 3.667954828756592e-12 error: 4.934497255248971e-12 iter_num: 500\n",
      "\n",
      "进度: 30/32  infid: 1.2418954753457001e-12 error: 1.8276491431379327e-12 iter_num: 1000\n",
      "\n",
      "进度: 31/32  infid: 6.15423663141712e-08 error: 8.736778889240071e-08 iter_num: 500\n",
      "\n",
      "进度: 32/32  infid: 2.9363868633280887e-06 error: 5.331333469471566e-06 iter_num: 1000\n",
      "\n",
      " mean of infid is： 4.913435873200866e-07\n",
      "\n",
      " mean of error is： 7.975641102900277e-07\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "circ += gate_0('02').on(0)\n",
    "circ += gate_0('03').on(0)\n",
    "circ += gate_0('04').on(0)\n",
    "circ += gate_0('05').on(0)\n",
    "circ += gate_0('06').on(0)\n",
    "circ += gate_0('07').on(0)\n",
    "circ += gate_0('08').on(0)\n",
    "circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "infid_list = [] # mean of infid\n",
    "error_list = [] # max of infid\n",
    "lr = 0.1\n",
    "single_iter = 500 # 每个循环包含 100 次训练\n",
    "max_iter = 40\n",
    "for i in range(len(u_mats)):\n",
    "    grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=0.05)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    m = 0 # 用于计数 \n",
    "    infid = 1\n",
    "    while True:\n",
    "        m += 1\n",
    "        for j in range(single_iter):\n",
    "            net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "            \n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        infid_tem = 1-np.real(np.mean([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        infid = min(infid, infid_tem)\n",
    "        if infid < 1e-5 or m >= max_iter:\n",
    "            break\n",
    "    infid_list.append(infid)\n",
    "    error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    error_list.append(error)\n",
    "    print(f\"\\n进度: {i+1}/{len(u_mats)} \",  'infid:', infid, 'error:', error, 'iter_num:', m*single_iter)\n",
    "#     print(params)\n",
    "print('\\n mean of infid is：', np.mean(infid_list))\n",
    "print('\\n mean of error is：', np.mean(error_list))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "64ba0ab5",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1.8107737531636303e-13, 1.638911228951656e-12, 6.056693477862751e-07, 2.1347088050571728e-06, 9.747758156208874e-14, 3.0732875283545624e-06, 5.942056846564014e-10, 2.05613304160579e-13, 1.525790693790441e-08, 1.4189760477734126e-12, 2.0250467969162855e-13, 2.505910823291657e-08, 1.6986412276764895e-13, 1.6753265441593612e-13, 1.5052958879380185e-11, 8.19366796633858e-12, 1.2323475573339238e-13, 2.786428195955537e-07, 3.3349264805249135e-06, 3.269758197532724e-08, 3.774820678259516e-09, 3.9190872769268026e-14, 1.83774966133754e-07, 1.520662510801074e-06, 3.531772652110021e-10, 1.5576429035490946e-13, 1.5156236327085182e-06, 1.162403506782539e-13, 3.667954828756592e-12, 1.2418954753457001e-12, 6.15423663141712e-08, 2.9363868633280887e-06]\n"
     ]
    }
   ],
   "source": [
    "print(infid_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "2a5297e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[3.2218672174622043e-13, 2.155164935402354e-12, 8.097765978876126e-07, 3.922348002727283e-06, 1.3100631690576847e-13, 5.7128267495487606e-06, 7.782662292399323e-10, 3.4372504842394846e-13, 2.224116224525119e-08, 1.9033663534173684e-12, 2.8477220581635265e-13, 3.80648668141248e-08, 2.297051437949449e-13, 2.311484337269576e-13, 2.121403053223503e-11, 1.1645906461410505e-11, 1.766364832178624e-13, 4.1575219345002523e-07, 4.669627582054581e-06, 6.487781767372525e-08, 5.339466979670249e-09, 6.716849298982197e-14, 2.5529041891569904e-07, 2.0835750229597494e-06, 5.186583384997334e-10, 2.0827783941967937e-13, 2.1022876081078223e-06, 1.8174350913113813e-13, 4.934497255248971e-12, 1.8276491431379327e-12, 8.736778889240071e-08, 5.331333469471566e-06]\n"
     ]
    }
   ],
   "source": [
    "print(error_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "3f9077e8",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "进度: 1/32  infid: 0.4879651704707578 error: 0.69830996261144 iter_num: 3500\n",
      "\n",
      "进度: 2/32  infid: 0.22674244437128 error: 0.30558891794989784 iter_num: 3500\n",
      "\n",
      "进度: 3/32  infid: 0.4882782116240555 error: 0.8168808402585265 iter_num: 3500\n",
      "\n",
      "进度: 4/32  infid: 0.23178333677566942 error: 0.3220099144380739 iter_num: 3500\n",
      "\n",
      "进度: 5/32  infid: 0.025865331066970754 error: 0.03391961073694194 iter_num: 3500\n",
      "\n",
      "进度: 6/32  infid: 0.3532569639554133 error: 0.4806290793444332 iter_num: 3500\n",
      "\n",
      "进度: 7/32  infid: 0.2392877390582333 error: 0.38128277952624734 iter_num: 3500\n",
      "\n",
      "进度: 8/32  infid: 0.002988577025838879 error: 0.005720781426915567 iter_num: 3500\n",
      "\n",
      "进度: 9/32  infid: 0.06312278397257953 error: 0.0843506406550889 iter_num: 3500\n",
      "\n",
      "进度: 10/32  infid: 0.26100334412228454 error: 0.3486808293748951 iter_num: 3500\n",
      "\n",
      "进度: 11/32  infid: 0.5188022719320307 error: 0.8673122242111251 iter_num: 3500\n",
      "\n",
      "进度: 12/32  infid: 0.5082539502635932 error: 0.7582591453772212 iter_num: 3500\n",
      "\n",
      "进度: 13/32  infid: 0.276920876507846 error: 0.36727878066656594 iter_num: 3500\n",
      "\n",
      "进度: 14/32  infid: 0.36176306862191965 error: 0.5186300916504649 iter_num: 3500\n",
      "\n",
      "进度: 15/32  infid: 0.009429280505722892 error: 0.012290204885242462 iter_num: 3500\n",
      "\n",
      "进度: 16/32  infid: 0.006047970888024334 error: 0.007785680424798214 iter_num: 3500\n",
      "\n",
      "进度: 17/32  infid: 0.13632510002122344 error: 0.1839327856931684 iter_num: 3500\n",
      "\n",
      "进度: 18/32  infid: 0.07384480126362003 error: 0.11044570232581796 iter_num: 3500\n",
      "\n",
      "进度: 19/32  infid: 0.2128052005467138 error: 0.3158282561101913 iter_num: 3500\n",
      "\n",
      "进度: 20/32  infid: 0.0026864998634544834 error: 0.01509111133455765 iter_num: 3500\n",
      "\n",
      "进度: 21/32  infid: 0.48615218581868413 error: 0.7337429888526092 iter_num: 3500\n",
      "\n",
      "进度: 22/32  infid: 0.250425841183448 error: 0.35357158165095237 iter_num: 3500\n",
      "\n",
      "进度: 23/32  infid: 0.0013502721246129168 error: 0.0033517948254756513 iter_num: 3500\n",
      "\n",
      "进度: 24/32  infid: 0.06009181010017073 error: 0.0835111846596086 iter_num: 3500\n",
      "\n",
      "进度: 25/32  infid: 0.18641605389100147 error: 0.2587425995504664 iter_num: 3500\n",
      "\n",
      "进度: 26/32  infid: 0.5550589880970995 error: 0.9514765985848216 iter_num: 3500\n",
      "\n",
      "进度: 27/32  infid: 0.01832060521870771 error: 0.02499851377787221 iter_num: 3500\n",
      "\n",
      "进度: 28/32  infid: 0.04226681827687462 error: 0.056989438727959585 iter_num: 3500\n",
      "\n",
      "进度: 29/32  infid: 0.12563412915630456 error: 0.1822603166920922 iter_num: 3500\n",
      "\n",
      "进度: 30/32  infid: 0.2213933191494063 error: 0.3007919230213256 iter_num: 3500\n",
      "\n",
      "进度: 31/32  infid: 0.2994321984102001 error: 0.5436731937470266 iter_num: 3500\n",
      "\n",
      "进度: 32/32  infid: 0.041598217991129616 error: 0.057901247554216106 iter_num: 3500\n",
      "\n",
      " mean of infid is： 0.21172854257108975\n",
      "\n",
      " mean of error is： 0.31828871002018877\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi/2\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "circ += gate_0('01').on(0)\n",
    "# circ += gate_0('02').on(0)\n",
    "# circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "infid_list = [] # mean of infid\n",
    "error_list = [] # max of infid\n",
    "lr = 0.1\n",
    "single_iter = 500 # 每个循环包含 100 次训练\n",
    "max_iter = 7\n",
    "for i in range(len(u_mats)):\n",
    "    grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "    Quantum_net = MQLayer(grad_ops)\n",
    "    opti = Adam(Quantum_net.trainable_params(), learning_rate=0.05)  \n",
    "    net = TrainOneStepCell(Quantum_net, opti)\n",
    "    m = 0 # 用于计数 \n",
    "    infid = 1\n",
    "    while True:\n",
    "        m += 1\n",
    "        for j in range(single_iter):\n",
    "            net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "            \n",
    "        params = abs(Quantum_net.weight.asnumpy())\n",
    "        final_state = []\n",
    "        for k in range(100): # 100 个测试点\n",
    "            sim.reset()\n",
    "            sim.set_qs(eval_x[k])\n",
    "            sim.apply_circuit(circ, params)\n",
    "            final_state.append(sim.get_qs())\n",
    "        infid_tem = 1-np.real(np.mean([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "        infid = min(infid, infid_tem)\n",
    "        if infid < 1e-5 or m >= max_iter:\n",
    "            break\n",
    "    infid_list.append(infid)\n",
    "    error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    error_list.append(error)\n",
    "    print(f\"\\n进度: {i+1}/{len(u_mats)} \",  'infid:', infid, 'error:', error, 'iter_num:', m*single_iter)\n",
    "#     print(params)\n",
    "print('\\n mean of infid is：', np.mean(infid_list))\n",
    "print('\\n mean of error is：', np.mean(error_list))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "18a568f1",
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.4879651704707578, 0.22674244437128, 0.4882782116240555, 0.23178333677566942, 0.025865331066970754, 0.3532569639554133, 0.2392877390582333, 0.002988577025838879, 0.06312278397257953, 0.26100334412228454, 0.5188022719320307, 0.5082539502635932, 0.276920876507846, 0.36176306862191965, 0.009429280505722892, 0.006047970888024334, 0.13632510002122344, 0.07384480126362003, 0.2128052005467138, 0.0026864998634544834, 0.48615218581868413, 0.250425841183448, 0.0013502721246129168, 0.06009181010017073, 0.18641605389100147, 0.5550589880970995, 0.01832060521870771, 0.04226681827687462, 0.12563412915630456, 0.2213933191494063, 0.2994321984102001, 0.041598217991129616]\n"
     ]
    }
   ],
   "source": [
    "print(infid_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "7bff955d",
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0.69830996261144, 0.30558891794989784, 0.8168808402585265, 0.3220099144380739, 0.03391961073694194, 0.4806290793444332, 0.38128277952624734, 0.005720781426915567, 0.0843506406550889, 0.3486808293748951, 0.8673122242111251, 0.7582591453772212, 0.36727878066656594, 0.5186300916504649, 0.012290204885242462, 0.007785680424798214, 0.1839327856931684, 0.11044570232581796, 0.3158282561101913, 0.01509111133455765, 0.7337429888526092, 0.35357158165095237, 0.0033517948254756513, 0.0835111846596086, 0.2587425995504664, 0.9514765985848216, 0.02499851377787221, 0.056989438727959585, 0.1822603166920922, 0.3007919230213256, 0.5436731937470266, 0.057901247554216106]\n"
     ]
    }
   ],
   "source": [
    "print(error_list)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1c0e5b49",
   "metadata": {},
   "source": [
    "# 采用 MQLayer abs 方法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f2464d9c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import sys\n",
    "from numpy import kron\n",
    "from mindquantum import *\n",
    "from scipy.linalg import expm\n",
    "import mindspore as ms\n",
    "from mindspore import ops\n",
    "ms.context.set_context(mode=ms.context.PYNATIVE_MODE, device_target=\"CPU\")\n",
    "from mindspore.nn import Adam, TrainOneStepCell\n",
    "from mindspore import Tensor\n",
    "from mindspore.common.parameter import Parameter\n",
    "from mindspore.common.initializer import initializer  \n",
    "ms.set_seed(1)\n",
    "np.random.seed(1)\n",
    "\n",
    "train_x = np.load('./src/1_qubit_train_x.npy', allow_pickle=True)\n",
    "eval_x = np.load('./src/1_qubit_eval_x.npy', allow_pickle=True)\n",
    "train_y = np.load('./src/1_qubit_train_y.npy', allow_pickle=True)\n",
    "eval_y = np.load('./src/1_qubit_eval_y.npy', allow_pickle=True)\n",
    "u_mats = np.load('./src/1_qubit_u.npy', allow_pickle=True)\n",
    "\n",
    "s_x = X.matrix()\n",
    "s_z = Z.matrix()\n",
    "one = I.matrix()\n",
    "dt = np.pi\n",
    "\n",
    "def _matrix_0(coeff):\n",
    "    return expm(-1j*(coeff*s_z+s_x)*dt)\n",
    "\n",
    "def _diff_matrix_0(coeff):\n",
    "    return -1j*_matrix_0(coeff)@(s_z*dt)\n",
    "\n",
    "gate_0 = gene_univ_parameterized_gate('gete_0', _matrix_0, _diff_matrix_0)\n",
    "\n",
    "circ = Circuit()\n",
    "circ += gate_0('00').on(0)\n",
    "# circ += gate_0('01').on(0)\n",
    "# circ += gate_0('02').on(0)\n",
    "# circ += gate_0('03').on(0)\n",
    "# circ += gate_0('04').on(0)\n",
    "# circ += gate_0('05').on(0)\n",
    "# circ += gate_0('06').on(0)\n",
    "# circ += gate_0('07').on(0)\n",
    "# circ += gate_0('08').on(0)\n",
    "# circ += gate_0('09').on(0)\n",
    "\n",
    "# circ += gate_0('10').on(0)\n",
    "# circ += gate_0('11').on(0)\n",
    "# circ += gate_0('12').on(0)\n",
    "# circ += gate_0('13').on(0)\n",
    "# circ += gate_0('14').on(0)\n",
    "# circ += gate_0('15').on(0)\n",
    "\n",
    "ham = Hamiltonian(QubitOperator('')) \n",
    "sim = Simulator('projectq', circ.n_qubits)\n",
    "sim_left = Simulator('projectq',circ.n_qubits)\n",
    "\n",
    "grad_ops = sim.get_expectation_with_grad(ham,\n",
    "                                         circ,\n",
    "                                         circ_left=Circuit(),\n",
    "                                         simulator_left=sim_left,\n",
    "                                         ansatz_params_name=circ.params_name)\n",
    "Quantum_net = MQLayer(grad_ops)\n",
    "opti = Adam(Quantum_net.trainable_params(), learning_rate=0.05)  \n",
    "net = TrainOneStepCell(Quantum_net, opti)\n",
    "\n",
    "infid_list = [] # mean of infid\n",
    "error_list = [] # max of infid\n",
    "lr = 0.05\n",
    "for i in range(len(u_mats)):\n",
    "    for j in range(len(train_x)):\n",
    "        net(Tensor(train_x[j]), Tensor(train_y[i,j]))\n",
    "\n",
    "    params = abs(Quantum_net.weight.asnumpy())\n",
    "    final_state_0 = []\n",
    "    for j in range(len(eval_x)):\n",
    "        sim.reset()\n",
    "        sim.set_qs(eval_x[j])\n",
    "        sim.apply_circuit(circ, params)\n",
    "        final_state.append(sim.get_qs())\n",
    "\n",
    "    infid_0 = 1-np.real(np.mean([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state_0), eval_y[i])]))\n",
    "    if infid_0 < 1e-7:\n",
    "        \n",
    "        \n",
    "        \n",
    "    infid_list.append(infid)\n",
    "    error = 1-np.real(np.min([np.abs(np.vdot(bra, ket)) for bra, ket in zip(np.array(final_state), eval_y[i])]))\n",
    "    error_list.append(error)\n",
    "    print(f\"\\n进度: {i+1}/{len(u_mats)} \",  'infid:', infid, 'error:', error, end=\"\")\n",
    "#     print(params)\n",
    "\n",
    "print('\\n mean of infid is：', np.mean(infid_list))\n",
    "print('\\n mean of error is：', np.mean(error_list))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "dfd96fa4",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9999999"
      ]
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "1-1e-7"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
